package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @program: sky-take-out
 * @description:
 * @author: fmp
 * @create: 2023-04-09 15:10
 * @Version 1.0
 **/
@Service
public class UserServiceImpl implements UserService {
    //抽取微信登录的校验接口
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Resource
    private WeChatProperties weChatProperties;
    @Resource
    private UserMapper userMapper;
    @Resource
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO userWxLogin(UserLoginDTO userLoginDTO) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("appid",weChatProperties.getAppid());
        hashMap.put("secret",weChatProperties.getSecret());
        hashMap.put("js_code",userLoginDTO.getCode());
        hashMap.put("grant_type","authorization_code");

        String wxLoginResult = HttpClientUtil.doGet(WX_LOGIN_URL, hashMap);
        JSONObject jsonObject = JSON.parseObject(wxLoginResult);
        String openId = jsonObject.getString("openid");
        //判断当前用户表中是否存在该openId对应的用户信息
        User user = userMapper.selectUserByOpenId(openId);
        if (Objects.isNull(user)) {
            //如果没有查询对应openId的用户信息,封装一个User插入到表中
            user = User.builder().openid(openId).createTime(LocalDateTime.now()).build();
            userMapper.insertUser(user); //▲返回主键
        }
        //生成令牌基于JwtUtil
        HashMap<String, Object> claimsMap = new HashMap<>();
        claimsMap.put(JwtClaimsConstant.USER_ID, user.getId()); //部分(2) userId=值
        String jwtToken = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claimsMap);
        return UserLoginVO.builder().id(user.getId()).openid(user.getOpenid()).token(jwtToken).build();

    }
}
